package com.pay.clickevent

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.app.ProgressDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Build
import android.support.v7.app.AlertDialog
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityManager
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.Toast
import com.pay.clickevent.Step.*
import org.json.JSONObject
import java.lang.Exception


/**
 * 继承自无障碍服务
 *
 *
 * <p>
 * 在配置好AccessibilityService后，而且系统“辅助设置”已打开配置过的AccessibilityService，刚开始能用，但莫名出现onAccessibilityEvent事件接收不到的情况，原因只有一条：
 * 程序出现了ANR，崩溃后AccessibilityServices就失效了，重启手机即可
 * </p>
 */
/**
 *
 */
class ClickService : AccessibilityService() {


    override fun onAccessibilityEvent(event: AccessibilityEvent) {
//        Log.e(TAG, event.className.toString())
//        Log.e(TAG, event.packageName.toString())
//        Log.e(TAG, event.eventType.toString())
//        Log.e(TAG, event.text.toString())


        try {
            when (event.eventType) {
                AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
                    Thread.sleep(1000)
                    if (Step.stasts && step.equals(TOPersonInfo) && "com.eg.android.AlipayGphone.AlipayLogin".equals(event.className)) {
                        //到个人中心
                        step = TOAccountInfo
                        var list: List<AccessibilityNodeInfo> = event.source.findAccessibilityNodeInfosByViewId("android:id/tabcontent")
                        var node: AccessibilityNodeInfo = list.get(0).getChild(0).getChild(2).getChild(1).getChild(0)
                        node.performAction(AccessibilityNodeInfo.ACTION_CLICK)


                    }
                    if (step.equals(TOAccountInfo) && "com.alipay.mobile.security.personcenter.PersonCenterActivity".equals(event.className)) {
                        step = BackTOPersonInfo
                        var list: List<AccessibilityNodeInfo> = event.source.findAccessibilityNodeInfosByText("个人主页")
                        var node: AccessibilityNodeInfo = list.get(0).parent.parent.parent.parent
                        node.performAction(AccessibilityNodeInfo.ACTION_CLICK)

                    }
                    if (step.equals(BackTOPersonInfo) && "com.alipay.android.phone.wallet.profileapp.ui.ProfileActivity_".equals(event.className)) {
                        step = BackTOMy
                        var list: List<AccessibilityNodeInfo> = event.source.findAccessibilityNodeInfosByViewId("android:id/content")
                        var accountNode: AccessibilityNodeInfo = list.get(0).getChild(0).getChild(0).getChild(2).getChild(0).getChild(0).getChild(0).getChild(1)
                        account = accountNode.text.toString()
                        Toast.makeText(this, "支付宝账号..." + account, Toast.LENGTH_LONG).show()
                        Log.e(TAG, "支付宝账号..." + account)
                        var backNode: AccessibilityNodeInfo = list.get(0).getChild(0).getChild(1).getChild(0).getChild(1).getChild(0)
                        backNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)

                    }
                    if (step.equals(BackTOMy) && "com.alipay.mobile.security.personcenter.PersonCenterActivity".equals(event.className)) {
                        step = ToBillList
                        var list: List<AccessibilityNodeInfo> = event.source.findAccessibilityNodeInfosByViewId("android:id/content")
                        var backNode: AccessibilityNodeInfo = list.get(0).getChild(0).getChild(0).getChild(0).getChild(0).getChild(0)
                        backNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)

                    }
                    if (step.equals(ToBillList) && "com.eg.android.AlipayGphone.AlipayLogin".equals(event.className)) {


                        if (jobNun > 600) {
                            //上线时间到了，自动下线
                            println("自动下线*****************")
                            Step.stasts = false
                            jobNun = 0
                            step = Step.TOPersonInfo
                            val intent = Intent()
                            // 为Intent设置Action、Category属性
                            intent.action = Intent.ACTION_MAIN// "android.intent.action.MAIN"
                            intent.addCategory(Intent.CATEGORY_HOME) //"android.intent.category.HOME"
                            startActivity(intent)

                        } else {

                            step = GetFirstBillInfoAndDelFirstBill
                            var list: List<AccessibilityNodeInfo> = event.source.findAccessibilityNodeInfosByText("账单")
                            var backNode: AccessibilityNodeInfo = list.get(0).parent.parent.parent.parent
                            Thread.sleep(2000)
                            backNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        }
                    }



                    if (step.equals(GetFirstBillInfoAndDelFirstBill) && "com.alipay.mobile.bill.list.ui.BillMainListActivity".equals(event.className)) {

                        println(GetFirstBillInfoAndDelFirstBill)
                        if (Step.stasts && jobNun < 550) {
                            var heartBeat = HttpUtil.heartBeat(account)
                            if (null == heartBeat) {
                                step = ""
                                print("上传心跳失败,请检查网络环境...")
                            }
                        }
                        //获取账单信息
                        var list: List<AccessibilityNodeInfo> = event.source.findAccessibilityNodeInfosByText("收钱码收款")

                        println(list.size)
                        if (0 == list.size) {
                            //没有账单信息
                            step = ToBillList
                            var BackList: List<AccessibilityNodeInfo> = event.source.findAccessibilityNodeInfosByText("账单")
                            var backNode: AccessibilityNodeInfo = BackList.get(0).parent.parent.getChild(0)
                            Thread.sleep(5000)
                            backNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)


                        } else {
                            //发现账单
                            var nodeInfoMoney: AccessibilityNodeInfo = list.get(0).parent.getChild(1)
                            var nodeInfoDate: AccessibilityNodeInfo = list.get(0).parent.parent.getChild(2).getChild(0).getChild(0)
                            var nodeInfoTime: AccessibilityNodeInfo = list.get(0).parent.parent.getChild(2).getChild(0).getChild(1)

                            var result: JSONObject? = HttpUtil.PostBill(account, nodeInfoMoney.text.toString(), nodeInfoDate.text.toString(), nodeInfoTime.text.toString())

                            //  println(result)
                            if (null !== result && "SUCCESS".equals(result!!.getString("RECODE"))) {

                                //上传成功，删除订单
                                step = CheckDelFirstBill
                                var nodeInfo: AccessibilityNodeInfo = list.get(0).parent.parent.parent.parent
                                Thread.sleep(2000)
                                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK)

                            } else {
                                //上传失败返回列表
                                step = ToBillList
                                var BackList: List<AccessibilityNodeInfo> = event.source.findAccessibilityNodeInfosByViewId("android:id/content")
                                var backNode: AccessibilityNodeInfo = BackList.get(0).getChild(0).getChild(0).getChild(0).getChild(0).getChild(0).getChild(0).getChild(0).getChild(0)
                                Thread.sleep(5000)
                                backNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)


                            }

                        }


                    }
                    if (step.equals(CheckDelFirstBill) && "com.alipay.mobile.antui.dialog.AUListDialog".equals(event.className)) {
                        //确认删除
                        step = GetFirstBillInfoAndDelFirstBill
                        var list: List<AccessibilityNodeInfo> = event.source.findAccessibilityNodeInfosByText("删除")
                        println("删除订单")
                        list.get(0).parent.performAction(AccessibilityNodeInfo.ACTION_CLICK)


                    }


                }

            }

        } catch (e: Exception) {
            e.printStackTrace()

        }


    }


    override fun onInterrupt() {
        Log.e(TAG, "授权中断")
        //服务中断，如授权关闭或者将服务杀死
    }

    override fun onServiceConnected() {

        super.onServiceConnected()
        Log.e(TAG, "service1授权成功")
        Toast.makeText(this, "授权成功...", Toast.LENGTH_SHORT).show()
        service = this
        val config = AccessibilityServiceInfo()
        //配置监听的事件类型为界面变化|点击事件
        config.eventTypes = AccessibilityEvent.TYPES_ALL_MASK
        config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC


        if (Build.VERSION.SDK_INT >= 16) {
            config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
        }
        config.flags = config.flags or AccessibilityServiceInfo.FLAG_REQUEST_ENHANCED_WEB_ACCESSIBILITY
        this.serviceInfo = config

    }


    companion object {
        var jobNun = 0

        var account: String = "" //支付宝账号
        var step: String? = TOPersonInfo //操作步骤,默认到我的

        val TAG = "ClickService"
        var service: ClickService? = null
        val targetPackageName = "com.eg.android.AlipayGphone"


        /**
         * 判断当前服务是否正在运行
         */
        val isRunning: Boolean
            get() {
                if (service == null) {
                    return false
                }
                val accessibilityManager = service!!.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
                val info = service!!.serviceInfo ?: return false
                val list = accessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC)
                val iterator = list.iterator()

                var isConnect = false
                while (iterator.hasNext()) {
                    val i = iterator.next()
                    if (i.id == info.id) {
                        isConnect = true
                        break
                    }
                }
                return isConnect
            }
    }


    override fun onUnbind(intent: Intent?): Boolean {
        service = null
        return super.onUnbind(intent)
    }


}
